package com.huawei.petapp2.activity;


import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.R;
import com.huawei.petapp2.activity.widget.BaseActivity;
import com.huawei.petapp2.activity.widget.wrapper.ProgressWrapper;
import com.huawei.petapp2.activity.widget.wrapper.PtrWrapper;
import com.huawei.petapp2.activity.widget.wrapper.ToastWrapper;
import com.huawei.petapp2.adapter.OrderListAdapter;
import com.huawei.petapp2.address.manage.ManageAddressActivity;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.Order;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.network.UserManager;
import com.huawei.petapp2.network.api.ApiOrderList;
import com.huawei.petapp2.network.core.ApiPath;
import com.huawei.petapp2.network.core.ResponseEntity;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 订单页面
 */
public class OrderListActivity extends BaseActivity {

    private static final String EXTRA_ORDER_TYPE = "EXTRA_ORDER_TYPE";
    int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
    String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));
    final private static Gson gson=new GsonBuilder().serializeNulls().create();
    public static Intent getStartIntent(Context context, int type) {
        Intent intent = new Intent(context, com.huawei.petapp2.activity.OrderListActivity.class);
        intent.putExtra(EXTRA_ORDER_TYPE, String.valueOf(type));
        return intent;
    }

    @BindView(R.id.list_order)
    ListView orderListView;

    @BindView(R.id.standard_order_title)
    TextView TextView;

    @BindView(R.id.standard_toolbar_back)
    ImageView imageView;

    private PtrWrapper mPtrWrapper;
    private OrderAdapter mOrderAdapter;
    private ProgressWrapper mProgressWrapper;
    int mOrderType;
    List<Order> orders;
    Toolbar toolbar ;

    protected int getContentViewLayout() {
        return R.layout.activity_order_list;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_order_list;
    }

    @Override
    public void initView() {

        this.toolbar = findViewById(R.id.order_toolbar);
        this.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent=new Intent(getContext(), ManageAddressActivity.class);
               startActivity(intent);
            }
        });
        initOrderType();
        mPtrWrapper = new PtrWrapper(this) {
            @Override
            public void onRefresh() {
                OkHttpClient client = new OkHttpClient();
                Request request1 = new Request.Builder()//获取改用户全部地址
                        .url(HttpUrl.getBaseUrl()+"/order/list"+"/"+userid+"/"+mOrderType)
                        .addHeader("Token",token)
                        .build();

                client.newCall(request1).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();
                            Result result=gson.fromJson(results,Result.class);
                            System.out.println("新的获取订单请求请求OnintView"+result);
                            orders= DateUtil.getList8(result);
                            System.out.println("新的获取订单请求请求"+result);
                        }
                    }
                });

            }
        };

        mOrderAdapter = new OrderAdapter(mOrderType,getContext());
        orderListView.setAdapter(mOrderAdapter);
        //mPtrWrapper.postRefresh(50);

       /* mOrderAdapter = new OrderAdapter(mOrderType,getApplicationContext());
        orderListView.setAdapter(mOrderAdapter);
        mPtrWrapper.postRefresh(50);*/
    }

    @Override
    public void initData() {
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/order/list"+"/"+userid+"/"+mOrderType)
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();

                            Result result=gson.fromJson(results,Result.class);
                            System.out.println("新的获取订单请求请求"+result);
                            mOrderAdapter = new OrderAdapter(mOrderType,getContext());
                            orderListView.setAdapter(mOrderAdapter);
                            orders= DateUtil.getList8(result);
                            mPtrWrapper.postRefresh(50);
                            mOrderAdapter.reset(orders);

                        }
                    }
                });
        ///mPtrWrapper.postRefresh(50);
        //mOrderAdapter.reset(orders);
    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void onBusinessResponse(String apiPath, boolean success, ResponseEntity rsp) {
        switch (apiPath) {
            case ApiPath.ORDER_LIST:
                mPtrWrapper.stopRefresh();
                if (success) {
                    ApiOrderList.Rsp listRsp = (ApiOrderList.Rsp) rsp;
                   // mOrderAdapter.reset(listRsp.getOrderList());
                }
                break;
            case ApiPath.ORDER_CANCEL:
                mProgressWrapper.dismissProgress();
                if (success) {
                    ToastWrapper.show(R.string.order_is_canceled);
                    UserManager.getInstance().retrieveUserInfo();
                    mPtrWrapper.autoRefresh();
                }
                break;
            default:
                throw new UnsupportedOperationException(apiPath);
        }
    }

    private void initOrderType() {
        System.out.println("此时输出的"+getIntent().getStringExtra(EXTRA_ORDER_TYPE));
        int type = Integer.parseInt(getIntent().getStringExtra(EXTRA_ORDER_TYPE));
        switch (type) {
            case 1:
                this.mOrderType = 1;
                TextView.setText("待付款订单");
                break;
            case 0:
                this.mOrderType = 6;
                TextView.setText("已关闭订单");
                break;
            case 2:
                this.mOrderType = 2;
                TextView.setText("代发货订单");
                break;
            case 4:
                this.mOrderType = 4;
                TextView.setText("待评价订单");
                break;
            case 5:
                this.mOrderType = 5;
                TextView.setText("所有订单");
                break;
            default:
                throw new IllegalArgumentException(String.valueOf(type));
        }
    }

    @OnClick(R.id.standard_toolbar_back) void selectRegion() {
        Intent intent=new Intent(getContext(), HomeActivity.class);
        intent.putExtra( "id", 4);
        startActivity(intent);
    }

    private class OrderAdapter extends OrderListAdapter {
        OrderAdapter(int type,Context context) {
            super(type,context);
        }




        @Override
        protected void onOrderCancel(com.huawei.petapp2.entity.Order  order) {
            mProgressWrapper.showProgress(com.huawei.petapp2.activity.OrderListActivity.this);
            //取消订单操作
            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()//获取改用户全部地址
                    .url(HttpUrl.getBaseUrl()+"/order/cancel"+"/"+order.getOrderId()+"/"+6)
                    .addHeader("Token",token)
                    .build();
            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的获取订单请求请求"+result);
                        //刷新当前activity
                        Intent waitPay = OrderListActivity
                                .getStartIntent(getContext(), 1);
                        startActivity(waitPay);

                    }
                }
            });
            mPtrWrapper.autoRefresh();
        }

        @Override
        protected void onOrderPurchase(com.huawei.petapp2.entity.Order order) {

        }
    }

}
